<template>
  <div class="appointment-record">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <van-icon name="arrow-left" size="20" @click="goBack" />
      <h2>我的预约</h2>
      <div class="placeholder"></div>
    </div>
    
    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-buttons">
        <div 
          v-for="(filter, index) in filterOptions" 
          :key="index"
          :class="['filter-btn', { active: activeFilter === index }]"
          @click="setActiveFilter(index)"
        >
          {{ filter.label }}
        </div>
      </div>
    </div>

    <!-- 预约记录列表 -->
    <div class="records-container">
      <div v-if="loading" class="loading-state">
        <van-loading size="24" color="#667eea" />
        <p>加载中...</p>
      </div>
      <div v-else-if="filteredRecords.length === 0" class="empty-state">
        <van-icon name="records" size="48" color="#c8c9cc" />
        <p>您还没有预约记录</p>
      </div>
      
      <div v-else class="records-list">
        <div 
          v-for="record in filteredRecords" 
          :key="record.number"
          class="record-item"
          @click="handleRecordClick(record)"
        >
          <div class="record-header">
            <div class="record-title">
              <span class="company-name">{{ record.planName }}</span>
            </div>
            <div class="record-time">{{ record.dispatchtime }}</div>
          </div>
          
          <div class="record-details">
            <div class="detail-row">
              <span class="label">姓名：</span>
              <span class="value">{{ record.driverName }}</span>
            </div>
            <div class="detail-row">
              <span class="label">车牌号：</span>
              <span class="value">{{ record.licensePlate }}</span>
            </div>
            <div class="detail-row">
              <span class="label">货物名称：</span>
              <span class="value">{{ record.itemName }}</span>
            </div>
            <div class="detail-row">
              <span class="label">规格：</span>
              <span class="value">{{ record.itemModel || '-' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">发货方：</span>
              <span class="value">{{ record.sendoutCompany }}</span>
            </div>
            <div class="detail-row">
              <span class="label">预约码：</span>
              <span class="value code-value">{{ record.pickCode }}</span>
            </div>
          </div>
          
          <div class="record-footer">
            <span class="create-time">创建时间：{{ record.createTime }}</span>
            <van-icon name="arrow" size="14" color="#c8c9cc" />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="active" class="custom-tabbar" @change="onTabChange">
      <van-tabbar-item icon="home-o">
        <span>首页</span>
      </van-tabbar-item>
      <van-tabbar-item icon="qr">
        <span>二维码</span>
      </van-tabbar-item>
      <van-tabbar-item icon="user-o">
        <span>我的</span>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { showToast, Loading } from 'vant'
import { useRouter } from 'vue-router'
import api from '../api/index.js'
import {getWechatUnionId,getWechatOpenId} from '../store.js'

const active = ref(0) // 默认选中首页
const router = useRouter()
const activeFilter = ref(0)

// 筛选选项
const filterOptions = [
  { label: '全部', value: 'all' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已拒绝', value: 'rejected' }
]

// 预约记录数据
const appointmentRecords = ref([])
const loading = ref(false)

// 获取真实预约记录
const fetchAppointmentRecords = async () => {
  loading.value = true
  try {
    const fwid = getWechatOpenId();
    
    if (!fwid) {
      showToast('未获取到微信ID，请先从首页授权')
      loading.value = false
      return
    }
    
    console.log('使用的微信ID:', fwid)
    
    // 调用新的预约记录接口
    const response = await api.getWaybillList(fwid)
    console.log('预约记录响应:', response)
    
    // 检查API响应
    if (response && response.code === 200 && response.data) {
      // 确保赋值的是数组类型
      appointmentRecords.value = Array.isArray(response.data) ? response.data : []
      console.log('预约记录数据:', appointmentRecords.value)
    } else {
      showToast(response?.msg || '获取预约记录失败')
      console.error('获取预约记录失败:', response)
      appointmentRecords.value = []
    }
  } catch (error) {
    showToast('网络请求失败')
    console.error('获取预约记录时发生错误:', error)
    appointmentRecords.value = []
  } finally {
    loading.value = false
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchAppointmentRecords()
})

// 根据筛选条件过滤记录
const filteredRecords = computed(() => {
  const filterValue = filterOptions[activeFilter.value].value
  
  // 首先确保appointmentRecords.value是数组类型
  if (!Array.isArray(appointmentRecords.value)) {
    return []
  }
  
  // 确保只处理有效的记录对象，防止null或undefined导致的错误
  const validRecords = appointmentRecords.value.filter(record => 
    record && typeof record === 'object' && record.number !== undefined
  )
  
  if (filterValue === 'all') {
    return validRecords
  }
  return validRecords.filter(record => record.status === filterValue)
})

// 设置活跃筛选器
const setActiveFilter = (index) => {
  activeFilter.value = index
}

// 获取状态文本
// const getStatusText = (status) => {
//   const statusMap = {
//     pending: '待审核',
//     approved: '已通过',
//     rejected: '已拒绝'
//   }
//   return statusMap[status] || '未知'
// }

// 返回首页
const goBack = () => {
  router.push('/')
}

// 点击记录项
const handleRecordClick = (record) => {
  showToast(`查看预约详情：${record.type}`)
}

// 底部导航切换
const onTabChange = (index) => {
  switch (index) {
    case 0:
      router.push('/')
      break
    case 1:
      router.push('/qr-code')
      break
    case 2:
      router.push('/profile')
      break
  }
}
</script>

<style scoped>
/* 全局样式优化 - 允许垂直滚动 */
.appointment-record {
  background: linear-gradient(180deg, #f8faff 0%, #f0f4ff 100%);
  min-height: 100vh;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 12px 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #e8f4f8 100%);
  position: relative;
  flex-shrink: 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.nav-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 0 0;
  letter-spacing: 1px;
  flex: 1;
  text-align: center;
}

.nav-header .van-icon {
  color: #2c3e50;
  cursor: pointer;
  padding: 4px;
  transition: all 0.3s ease;
}

.nav-header .van-icon:hover {
  color: #667eea;
}

.placeholder {
  width: 28px;
  height: 28px;
}

/* 筛选条件 */
.filter-section {
  padding: 16px 16px 12px 16px;
  flex-shrink: 0;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  background: white;
  border-radius: 12px;
  padding: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-btn {
  flex: 1;
  padding: 10px 12px;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: #8f9bb3;
  cursor: pointer;
  transition: all 0.3s ease;
  background: transparent;
}

.filter-btn.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.filter-btn:hover:not(.active) {
  background: rgba(102, 126, 234, 0.05);
  color: #667eea;
}

/* 记录容器 */
.records-container {
  flex: 1;
  padding: 0 16px 20px 16px;
  overflow-y: auto;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-state p {
  margin: 16px 0 0 0;
  font-size: 16px;
  color: #667eea;
}

.empty-state p {
  margin: 16px 0 0 0;
  font-size: 16px;
  color: #8f9bb3;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(102, 126, 234, 0.08);
  position: relative;
  overflow: hidden;
}

.record-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.02), rgba(118, 75, 162, 0.02));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.record-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  border-color: rgba(102, 126, 234, 0.15);
}

.record-item:hover::before {
  opacity: 1;
}

.record-item:active {
  transform: translateY(0) scale(0.98);
}

/* 记录头部 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin: 0 0 12px 0;
  position: relative;
  z-index: 1;
}

.record-title {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.3;
}

.status-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  width: fit-content;
}

.status-badge.pending {
  background: rgba(255, 193, 7, 0.15);
  color: #f57c00;
}

.status-badge.approved {
  background: rgba(76, 175, 80, 0.15);
  color: #388e3c;
}

.status-badge.rejected {
  background: rgba(244, 67, 54, 0.15);
  color: #d32f2f;
}

.record-time {
  font-size: 14px;
  color: #667eea;
  font-weight: 500;
  white-space: nowrap;
  margin: 0 0 0 12px;
}

/* 记录详情 */
.record-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin: 0 0 12px 0;
  position: relative;
  z-index: 1;
}

.detail-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-row .label {
  font-size: 13px;
  color: #8f9bb3;
  min-width: 68px;
  flex-shrink: 0;
}

.detail-row .value {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
}

/* 预约码高亮样式 */
.detail-row .code-value {
  font-size: 14px;
  color: #667eea;
  font-weight: 600;
  letter-spacing: 1px;
  background: rgba(102, 126, 234, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
}

/* 记录底部 */
.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0 0 0;
  border-top: 1px solid rgba(102, 126, 234, 0.08);
  position: relative;
  z-index: 1;
}

.create-time {
  font-size: 12px;
  color: #c8c9cc;
}

/* 底部导航美化 */
.custom-tabbar {
  background: white;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(10px);
  padding: 2px 0;
  min-height: 48px;
  flex-shrink: 0;
}

.custom-tabbar .van-tabbar-item {
  color: #8f9bb3;
  transition: all 0.3s ease;
}

.custom-tabbar .van-tabbar-item--active {
  color: #667eea;
  font-weight: 600;
}

.custom-tabbar .van-tabbar-item--active .van-icon {
  transform: scale(1.1);
}

/* 响应式优化 */
@media screen and (max-width: 375px) {
  .header-title h2 {
    font-size: 18px;
  }
  
  .filter-btn {
    padding: 8px 10px;
    font-size: 13px;
  }
  
  .record-item {
    padding: 14px;
  }
  
  .company-name {
    font-size: 15px;
  }
  
  .detail-row .label {
    min-width: 64px;
    font-size: 12px;
  }
  
  .detail-row .value {
    font-size: 12px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.record-item {
  animation: fadeInUp 0.4s ease forwards;
}

.record-item:nth-child(1) { animation-delay: 0.1s; }
.record-item:nth-child(2) { animation-delay: 0.2s; }
.record-item:nth-child(3) { animation-delay: 0.3s; }
.record-item:nth-child(4) { animation-delay: 0.4s; }
.record-item:nth-child(5) { animation-delay: 0.5s; }

.filter-section {
  animation: fadeInUp 0.6s ease forwards;
}
</style>